#Canny边缘提取
import cv2 as cv
import numpy as np


#高斯模糊+灰度
def custom_threshold(image):
    blurred = cv.GaussianBlur(image, (1, 1), 0)
    gray = cv.cvtColor(blurred, cv.COLOR_RGB2GRAY) 
    #h, w =gray.shape[:2]
    #m = np.reshape(gray, [1,w*h])
    #mean = m.sum()/(w*h)
    #print("mean:",mean)
    #ret, binary =  cv.threshold(gray, mean, 255, cv.THRESH_TOZERO)
    #ret, binary = cv.threshold(gray,127,255,cv.THRESH_TOZERO)  
    #cv.namedWindow("blurred", cv.WINDOW_NORMAL)
    #cv.imshow("blurred", blurred)
    return gray

#Sobel算子
def custom_sobel(image):
    x = cv.Sobel(image,cv.CV_16S,1,0)
    #y = cv.Sobel(image,cv.CV_16S,0,1)
    absX = cv.convertScaleAbs(x)   # 转回uint8
    #absY = cv.convertScaleAbs(y)
    #dst = cv.addWeighted(absX,0.5,absY,0.5,0)
    #cv.imshow("absX", absX)
    #cv.imshow("absY", absY)
    #cv.namedWindow("sobel", cv.WINDOW_NORMAL)
    #cv.imshow("sobel", absX)
    return absX

#二值化+闭运算
def bin_threshold(image):
    ret, binary =  cv.threshold(image, 0, 255, cv.THRESH_OTSU + cv.THRESH_BINARY)
    kernel = np.ones((5,5),np.uint8)
    erosion = cv.morphologyEx(binary, cv.MORPH_CLOSE, kernel)
    #plt.subplot(1,2,1),plt.imshow(img,'gray')#默认彩色，另一种彩色bgr
    #plt.subplot(1,2,2),plt.imshow(erosion,'Result')
    #cv.imshow("Result", erosion)
    return binary

#轮廓检测
def Contours_test(dst, image):
    _, contours, hierarchy = cv.findContours(image, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)  
    cv.drawContours(dst, contours, -1, (0,0,255), 3)
    cv.imshow("Result", dst)


src = cv.imread("F:\\ml\\moban\\wowtest01.jpg")
#cv.namedWindow('input_image', cv.WINDOW_NORMAL) #设置为WINDOW_NORMAL可以任意缩放
#cv.imshow('input_image', src)
image1 = custom_threshold(src)
image2 = custom_sobel(image1)
image3 = bin_threshold(image2) 
Contours_test(src, image3)


cv.waitKey(0)
cv.destroyAllWindows()
